#include <stdio.h>
#include <string.h>
#include "createIdent.h"



void removeEntry (FILE *sourceFile , int curSourcePos, int sourceSize);
void copyEntryFile(FILE *src, FILE *dest);
void cleanFile(void);

int main(int argc, char *argv[])
{
	char login[40], car, erreur = TRUE;
	int size,  position=0,  currentPos;	

	if(argc != 2)									//Verification arguments
	{
        printf("Usage : delUser login\n");
        return 1;
    }

	FILE *identFile = fopen("../kernel/ident.txt","r+");
	fseek(identFile, 0, SEEK_END);			
	size = ftell(identFile);						// taille du fichier
	fseek(identFile, 0, SEEK_SET);			
	if (identFile != NULL)
	{
		while (position < size)
		{
			currentPos  = ftell(identFile);			// pour removeEntry
			fscanf(identFile,"%s",login);
			if (!strcmp(login,argv[1])) 			// si identique
			{
				erreur = FALSE;
				removeEntry(identFile,currentPos,size);
				break;
			}
			car =0;
			while (car != '\n') 					// enlève le password
				car = fgetc(identFile);
			position = ftell(identFile);	
		}
		fclose(identFile);
		if (erreur) 
			printf("Error !!! Login not found\n");
	}
	else
	{
		printf("Error !!! Use createIdent.o first\n");
		return -1;
	}
	return 0;
}


void removeEntry (FILE *sourceFile , int curSourcePos, int sourceSize) {
	int position=0;
	char car=0;
	FILE *destFile = fopen("file1.txt","w");
	fseek(sourceFile, 0, SEEK_SET);	
	while (position+1 < curSourcePos)		// partie avant le nom
	{
		copyEntryFile(sourceFile,destFile);
		position  = ftell(sourceFile);
	}
	fclose(destFile);
	
	destFile = fopen("file2.txt","w");

	fseek(sourceFile, curSourcePos, SEEK_SET);	
	while (car != '\n') 					// passe l'entree à enlever
		car = fgetc(sourceFile);

	while(position + 1 < sourceSize) 
	{
		copyEntryFile(sourceFile,destFile);
		position  = ftell(sourceFile);
	}
	fclose(destFile);	
	cleanFile();

	system("cat file1.txt file2.txt > ../kernel/ident.txt");
	system("rm file1.txt"); system("rm file2.txt");	
}

void copyEntryFile(FILE *src, FILE *dest)	
{
	char input[40];	

	fscanf(src,"%s",input);
	fprintf(dest,"%s",input);				// login
	fputc(' ',dest);
	fscanf(src,"%s",input);					// passwd
	fprintf(dest,"%s",input);		
	fputc('\n',dest);
}

/*
*	enleve le dernier /n si on demande d'effacer le dernier élément
*/
void cleanFile(void) {
	FILE *src = fopen("file2.txt","r");
	fseek(src,-2, SEEK_END);
	if ( fgetc(src) == ' ')			// vérifie si la fin du fichier est érronée
	{
		system("touch file3.txt");
		fclose(src);
		system("mv file3.txt file2.txt");
	}
	else 
		fclose (src);
}
	
